import Taro from "@tarojs/taro";
import api from "@/service/apiRequest";
import { getTerminalType } from "@/utils";

/**
 * 获取小程序的appId
 * @returns 小程序appId
 */
export const getAppId = (appId: string =""): string => {
  let clientType = getTerminalType();
  if (clientType === "H5") {
    return appId || "";
  }
  let accountInfo = Taro.getAccountInfoSync();
  return accountInfo.miniProgram ? accountInfo.miniProgram.appId : "";
}

const userLogin = () => {
  return new Promise((resolve) => {
    Taro.login({
      success(result) {
        console.log("登录成功:", result);        
        if (result.code) {              
          resolve(result.code);
        }
      },
      fail(err) {
        console.log("登录失败:", err);
        resolve("");
      },
    })
  })
}

export const loginStatusFn = () => {
  return new Promise((resolve) => {
    Taro.checkSession({
      success(res) {
        //session_key 未过期，并且在本生命周期一直有效
        console.log("微信认证未过期：", res);
        resolve('');
      },
      fail: async function(err) {
        // session_key 已经失效，需要重新执行登录流程
        console.log("微信认证异常：", err);
        let code = await userLogin();
        resolve(code);
      },
    })
  })
  
}

export const getUserInfo = async (isRefresh = false) => {
  let authCode = isRefresh ? await userLogin() : await loginStatusFn();
  if (authCode) {
    console.log(authCode, "code===");
    let res = await api.post("/api/auth/register-login", {authCode});
    if (res && res.token) {
      Taro.setStorageSync("User-Token", res.token);
    }
    return res;
  }
}